// Widgets/Personals/Trends/Trends.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { queryPetTrendsInfo , updatePetTrendsSupport } from '../../../api/pet';
import { throttle , checkFile } from '../../../utils/util';
const regeneratorRuntime = require('../../../common/runtime');
Component({

  /**
   * 组件的属性列表
   */
  properties: {

  },
  /**
   * 组件的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
    screenHeight: wx.getSystemInfoSync().screenHeight,
    CustomBar: app.globalData.CustomBar,
    tabbarHeight: wx.getSystemInfoSync().screenHeight - wx.getSystemInfoSync().safeArea.bottom + 60,
    page: 0,
    dataList: [],
    scrollHeight: 0,
    loading: true,
    noMore: false,
    loadingFailed: false,
    isReachBottom: false,
    refresher: false,
  },
  lifetimes: {
    attached: function() {
      let _this = this;
      // 在组件实例进入页面节点树时执行
      console.log('动态模块')
      _this._queryPetTrendsInfo();
    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 加载更多数据
    onLoadMore: throttle(function(){
      console.log('上拉加载')
      if(this.data.isReachBottom){
        this._queryPetTrendsInfo();
      }
    },500),
    onPullDownRefresh: function(){
      let _this = this;
      _this.setData({
        page: 0,
        isReachBottom: false,
        noMore: false,
        loading: false,
        loadingFailed: false,
      })
      this._queryPetTrendsInfo();
      setTimeout(()=>{
        wx.stopPullDownRefresh({
          success: (res) => {
            console.log(res,'刷新成功')
            _this.setData({
              refresher: false
            })
            wx.showToast({
              title: '刷新成功',
              icon: 'none',
            })
          },
        })
      },1500)
    },
    _queryPetTrendsInfo(){
      let _this = this;
      queryPetTrendsInfo({isOpen: '1',page: _this.data.page,isNeedUserId: '0',userId: wx.getStorageSync('userId')})
      .then(res => {
        if(res.success){
          var list = _this.data.dataList;
          var arr = [];
          for (let index = 0; index < res.data.content.length; index++) {
            const item = res.data.content[index];
            if(item.fileUrl && item.fileUrl != 'null' && item.fileUrl != ''){
              item.imageUrl = item.fileUrl.split(',')
              var fileList = []
              for (let j = 0; j < item.imageUrl.length; j++) {
                const img = item.imageUrl[j];
                var types = checkFile(img);
                if(types == 'video'){
                  fileList.push({url: img,isVideo: true,deletable: true})
                }else if(types == 'image'){
                  fileList.push({url: img,isImage: true,deletable: true})
                }
              }
              item.imageUrl = fileList;
            }else{
              item.imageUrl = []
            }
            arr.push(item);
          }
          if(_this.data.page == 0){
            list = arr;
          }else{
            list = list.concat(arr);
          }
          _this.setData({
            dataList: list,
            total: res.data.totalElements,
            page: _this.data.page+1,
          })
          if(_this.data.page * 10 >= res.data.totalElements){
            _this.setData({
              isReachBottom: false,
              noMore: true,
              loading: false,
              loadingFailed: false,
            })
          }else{
            _this.setData({
              isReachBottom: true,
              noMore: false,
              loading: false,
              loadingFailed: false,
            })
          }
        }else{
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      })
    },
    // 查询单条评论数据
    getOneData(id){
      return new Promise((resolve,reject) => {
        queryPetTrendsInfo({id: id,isNeedUserId: '0',userId: wx.getStorageSync('userId')})
        .then(res => {
          if(res.success){
            var item = res.data.content[0];
            if(item.fileUrl && item.fileUrl != 'null' && item.fileUrl != ''){
              item.imageUrl = item.fileUrl.split(',')
              var fileList = []
              for (let j = 0; j < item.imageUrl.length; j++) {
                const img = item.imageUrl[j];
                var types = checkFile(img);
                if(types == 'video'){
                  fileList.push({url: img,isVideo: true,deletable: true})
                }else if(types == 'image'){
                  fileList.push({url: img,isImage: true,deletable: true})
                }
              }
              item.imageUrl = fileList;
            }else{
              item.imageUrl = []
            }
            resolve(item)
          }else{
            reject(res.errMessage)
          }
        })
      })
    },
    // 点赞评论
    supports(e){
      let _this = this;
      let item = e.target.dataset.item||e.currentTarget.dataset.item;
      console.log(item,'item')
      updatePetTrendsSupport({trendsId: item.id,isSupport: item.isSupport == '1' ? '0' : '1'})
      .then(async res => {
        if(res.success){
          wx.showToast({
            title: item.isSupport == '1' ? '取消点赞' : '点赞成功',
            icon: 'success',
          })
          try {
            var items = await _this.getOneData(item.id);
            var index = _this.data.dataList.findIndex(items => items.id == item.id);
            var list = _this.data.dataList;
            list[index] = items;
            _this.setData({
              dataList: list,
            })
          } catch (error) {
            wx.showToast({
              title: error,
              icon: 'none'
            })
          }
        }else{
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      })
    },
    // 页面跳转
    goNext(e){
      let _this = this;
      let type = e.target.dataset.type||e.currentTarget.dataset.type;
      let url = e.target.dataset.name||e.currentTarget.dataset.name;
      let item = e.target.dataset.item||e.currentTarget.dataset.item;
      wx.setStorageSync('selNearByStore','0');
      // console.log(JSON.stringify(item))
      // return
      if(item){
        if(type == 1){
          wx.switchTab({
            url: `${url}`,
          })
        }else{
          wx.navigateTo({
            url: `${url}?item=${JSON.stringify(item)}`,
            events: {
              'updateTrends': async function(data){
                console.log('alksjdaklsd',data)
                // _this.getOneData(data);
                var items = await _this.getOneData(data);
                var index = _this.data.dataList.findIndex(items => items.id == data);
                var list = _this.data.dataList;
                list[index] = items;
                _this.setData({
                  dataList: list,
                })
              },
              'addTrends': function(data){
                _this.resetData();
              }
            }
          })
        }
      }else{
        if(type == 1){
          wx.switchTab({
            url: `${url}`,
          })
        }else{
          wx.navigateTo({
            url: `${url}`,
            events: {
              'updateTrends': function(data){
                _this.getOneData(data.id);
              },
              'addTrends': function(data){
                _this.resetData();
              }
            }
          })
        }
      }
    },
    // 初始化
    resetData(){
      let _this = this;
      _this.setData({
        page: 0,
        isReachBottom: false,
        noMore: false,
        loading: false,
        loadingFailed: false,
      })
      _this._queryPetTrendsInfo();
    },
    // 查看图片
    goLink(e){
      let url = e.target.dataset.url||e.currentTarget.dataset.url;
      let item = e.target.dataset.item||e.currentTarget.dataset.item;
      wx.navigateTo({
        url: `/pages/Link/LinkImg/LinkImg?url=${encodeURIComponent(url)}&title=${JSON.stringify(item.content)}`,
      })
    },
    // 查看视频
    goVideo(e){
      let url = e.target.dataset.url||e.currentTarget.dataset.url;
      let item = e.target.dataset.item||e.currentTarget.dataset.item;
      wx.navigateTo({
        url: `/pages/Link/LinkVideo/LinkVideo?url=${encodeURIComponent(url)}&title=${JSON.stringify(item.content)}`,
      })
    },
  },
})